package com.kerrykidz.system.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.kerrykidz.common.Constants;
import com.kerrykidz.common.PrimaryKeyGenerator;
import com.kerrykidz.common.PrimaryKeyGenerator.BusinessType;
import com.kerrykidz.common.service.ICommonService;
import com.kerrykidz.membership.dao.model.CusClassImpDtlEntity;
import com.kerrykidz.membership.dao.model.CusClassImpEntity;
import com.kerrykidz.membership.dao.model.CusMemClassEntity;
import com.kerrykidz.scminvoicing.dao.model.GblScmPrdEntity;
import com.kerrykidz.scminvoicing.service.IScmInvocingProductInfoService;
import com.kerrykidz.system.dao.model.GblSecBranEntity;
import com.kerrykidz.system.dao.model.SysParaEntity;
import com.kerrykidz.system.service.ICusClassImpDtlService;
import com.kerrykidz.system.service.ICusClassImpService;
import com.kerrykidz.system.service.ICusMemClassService;
import com.kerrykidz.system.service.ISysBarCodeService;
import com.kerrykidz.system.util.DateUtil;
import com.kerrykidz.system.util.UserUtil;
import com.kerrykidz.system.vo.UserInfo;
import com.rdp.framework.exception.RDPException;
import com.rdp.util.office.ExcelUtil;

@RequestMapping("signClass")
@Controller
public class CusMemClassController {
	@Autowired
	private ICusMemClassService iCusMemClassService;
	@Autowired
	private ICusClassImpService iCusClassImpService;
	@Autowired
	private ICusClassImpDtlService iCusClassImpDtlService;
	@Autowired
	private ISysBarCodeService iSysBarCodeService;
	@Autowired
	private ICommonService commonService;
	@Autowired
	private IScmInvocingProductInfoService productInfoService;

	@RequestMapping("/memClass")
	public ModelAndView memClass() throws RDPException {
		String branId = UserUtil.getUserFromSession().getBranId();
		List<GblSecBranEntity> list = iSysBarCodeService.selectBranList(branId);
		List<CusMemClassEntity> list1 = iCusMemClassService.select(branId);
		ModelAndView mv = new ModelAndView("system/system_kech");
		List<GblScmPrdEntity> list2 = productInfoService
				.findAllLessonsProduct();
		mv.addObject("list", list);
		mv.addObject("list1", list1);
		mv.addObject("list2", list2);
		mv.addObject("branId", branId);
		mv.addObject("key", Constants.SYS_BASE_PATH_SIGNFORM);
		mv.addObject("fkAttFile", "课程签到表.xlsx");
		return mv;
	}

	@RequestMapping("/memClassDetail")
	@ResponseBody
	public CusClassImpDtlEntity findClass(CusClassImpDtlEntity dtlEntity)
			throws RDPException {
		CusClassImpDtlEntity dtlEntity1 = iCusClassImpDtlService
				.findSignMsg(dtlEntity);
		return dtlEntity1;
	}

	/**
	 * @throws ParseException
	 * @throws RDPException
	 * @throws UnsupportedEncodingException
	 * @throws UnsupportedEncodingException
	 * @Title: uploadSignFile
	 * @Description: 上传课程签到附件
	 * @param: @param file
	 * @date: 2014年9月15日
	 * @return: String
	 * @throws
	 */
	@RequestMapping("/uploadFile")
	@ResponseBody
	public String uploadSignFile(
			@RequestParam(value = "file", required = false) MultipartFile file)
			throws UnsupportedEncodingException, RDPException, ParseException {
		UserInfo user = UserUtil.getUserFromSession();
		if(null == user)
			return null;
		CusClassImpDtlEntity dtlEntity = new CusClassImpDtlEntity();
		CusClassImpEntity impEntity = new CusClassImpEntity();
		SysParaEntity para = commonService.findSysParaById(Constants.SYS_BASE_PATH_SIGN);
		if(para == null){
			return null;
		}
		String fileName = file.getOriginalFilename();
		String filePath = para.getParaValue()+ "\\" + fileName;
		File targetFile = new File(para.getParaValue(), fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		String pkClassimpId = PrimaryKeyGenerator.getPrimaryKey(
				BusinessType.KC, user.getAbbrCode());
		ExcelUtil excel = new ExcelUtil(filePath);
		String strKeys = "学员编号,学员姓名,总课时,签到时间,学员签名,家长签名";
		List<Map<String, String>> xlist = excel.importExcelToMapForClass(strKeys);
		Map<String, String> map1 = (Map<String, String>) xlist.get(0);
		Map<String, String> map2 = (Map<String, String>) xlist.get(1);
		impEntity.setPkClassimpId(pkClassimpId);
		String str = (String) map1.get("学员编号");
		String[] tempStr = str.split("：");
		impEntity.setFkPrdId(tempStr[1]);
		String str1 = (String) map2.get("学员编号");
		String[] tempStr1 = str1.split("：");
		impEntity.setClassTime(tempStr1[1]);

		String str2 = (String) map2.get("签到时间");
		String[] tempStr2 = str2.split("：");
		impEntity.setTeacher(tempStr2[1]);
		impEntity.setFkBranId(user.getBranId());
		impEntity.setModiBy(user.getUserId());
		iCusClassImpService.addSignMsg(impEntity);
		for (int i = 3; i < xlist.size(); i++) {
			Map<String, String> map = (Map<String, String>) xlist.get(i);
			if(null != map.get("签到时间") && null != map.get("学员签名")){
				dtlEntity.setFkClassimpId(pkClassimpId);
				dtlEntity.setFkMemclassId((String) map.get("学员编号"));
				String signed = (String) map.get("签到时间");
				Date signedTime = null;
				if(signed.length() >16)
					signedTime = DateUtil.getDate(signed, "yyyy-MM-dd HH:mm:ss");
				else
					signedTime = DateUtil.getDate(signed, "yyyy-MM-dd HH:mm");
				dtlEntity.setSignedTime(signedTime);
				dtlEntity.setSignedBy((String) map.get("学员签名"));
				dtlEntity.setGuaSign((String) map.get("家长签名"));
				CusClassImpDtlEntity dtlEntity1 = iCusClassImpDtlService
						.findReSigned(dtlEntity);
				if (dtlEntity1 != null) {
					continue;
				}
				iCusClassImpDtlService.insertSignMsg(dtlEntity);
			}
		}
		fileName = URLEncoder.encode(fileName, "UTF-8");
		return fileName;
	}

	/**
	 * @throws RDPException
	 * @Title: signedHistory
	 * @Description: 签到历史
	 * @param:
	 * @date: 2014年9月26日
	 * @return: List
	 * @throws
	 */
	@RequestMapping("/signedHistory")
	@ResponseBody
	public List<CusClassImpDtlEntity> signedHistory(
			CusClassImpDtlEntity dtlEntity) throws RDPException {
		return iCusClassImpDtlService.signedHistory(dtlEntity);
	}
	
	/**
	 * 课程签到导出
	 * @throws RDPException
	 * @date: 2014年11月18日
	 */
	@RequestMapping(value="/courseSignExport")
	public void courseSignExport(@RequestParam("courseId") String courseId,@RequestParam("courseName") String courseName, HttpServletResponse response) throws RDPException{
		UserInfo user = UserUtil.getUserFromSession();
		if(null != user && StringUtils.isNotBlank(user.getBranId())){
			iCusMemClassService.courseSignExport(courseId,courseName,user.getBranId(),response);
		}
	}

}
